package com.wlsk.license.controller.plate;

import com.wlsk.license.common.enums.CharterPlateStatusEnum;
import com.wlsk.license.common.result.Result;
import com.wlsk.license.dto.BaseUserReqDto;
import com.wlsk.license.dto.Test2Vo;
import com.wlsk.license.dto.UploadFileReqDto2;
import com.wlsk.license.dto.request.*;
import com.wlsk.license.dto.response.*;
import com.wlsk.license.dto.response.feign.UserResDto;
import com.wlsk.license.service.IFileUploadService;
import com.wlsk.license.service.IPlateGenerateService;
import com.wlsk.license.service.IPlateManageService;
import com.wlsk.license.service.ISysDictService;
import com.wlsk.license.service.zpff.CharterApplyLicense;
import com.wlsk.license.service.zpff.RtabHelper;
import com.wlsk.license.service.zpff.RtabTokenHelper;
import com.zhongjinfeng.util.helper.StringHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @description: 包车牌管理控制
 * @author: 钟金凤
 * @date: 2025/9/23
 */
@Slf4j
@RestController
@AllArgsConstructor
@Api(tags = "包车牌管理")
@RequestMapping("/plate/manage")
public class PlateManageController {

    @Autowired
    IPlateManageService plateOwnerService;

    @Autowired
    IFileUploadService fileUploadService;

    @Autowired
    private IPlateGenerateService plateGenerateService;

    /**
     * 申请第一步  业务信息获取
     *
     * @param reqDto
     * @return
     */
    @ApiOperation(value = "通过用户id查询该商家道路经营许可证再获取业户信息")
    @PostMapping("/getCooperateCode")
    public Result<?> getCooperateCode(@RequestBody BaseUserReqDto reqDto) {
        return plateOwnerService.getCooperateCode(reqDto);
    }

    /**
     * 申请第一步  业务信息获取
     *
     * @param reqDto
     * @return
     */
    @ApiOperation(value = "通过经营许可证去zz系统获取业户信息")
    @PostMapping("/getOwnerInfo")
    public Result<?> getOwnerInfo(@RequestBody PlateOwnerReqDto reqDto) {
        return plateOwnerService.getOwnerInfo(reqDto);
    }

    /**
     * 申请第一步  业务信息获取
     *
     * @param reqDto
     * @return
     */
    @ApiOperation(value = "通过PlateId获取业户信息")
    @PostMapping("/getOwnerInfo2")
    public Result<?> getOwnerInfo2(@RequestBody GetOwnerInfoReqDto reqDto) {
        return plateOwnerService.getOwnerInfo2(reqDto);
    }

    /**
     * 申请第一步  业务信息反馈
     *
     * @param reqDto
     * @return
     */
    @ApiOperation(value = "反馈业户信息")
    @PostMapping("/postOwnerInfo")
    public Result<PlateOwnerPostResultDto> postOwnerInfo(@RequestBody @Validated PlateOwnerPostReqDto reqDto) {
        return plateOwnerService.postOwnerInfo(reqDto);
    }

    /**
     * 申请第二步  运次信息-->获取行政区划
     *
     * @param reqDto
     * @return
     */
    @ApiOperation(value = "获取行政区划")
    @PostMapping("/getCitiesDj")
    public Result<?> getCitiesDj(@RequestBody @Validated CityCodeReqDto reqDto) {
        return plateOwnerService.getCitiesDj(reqDto);
    }

    /**
     * 申请第二步  运次信息-->反馈运管运次信息
     */
    @ApiOperation(value = "反馈运管运次信息")
    @PostMapping("/postTransportatinCycle")
    public Result<?> postTransportatinCycle(@RequestBody PostPlateLineReqDto reqDto) {
        if (reqDto.getPlateLineInfo() == null) {
            return Result.failed("没有运次消息");
        }
        if (reqDto.getPlateLineInfo().getLimitEnd().isBefore(reqDto.getPlateLineInfo().getLimitStart())) {
            return Result.failed("用车结束时间必须大于用车开始时间");
        }
        return plateOwnerService.postTransportatinCycle(reqDto);
    }

    /**
     * 申请第二步  运次信息-->获取运次信息
     */
    @ApiOperation(value = "获取运次信息")
    @PostMapping("/getTransportatinCycle")
    public Result<PlateLineInfoResultDto> getTransportatinCycle(@RequestBody GetTransportatinCycleReq reqDto) {
        return plateOwnerService.getTransportatinCycle(reqDto);
    }

    /**
     * 申请第三步  车辆信息-->通过车牌号和经营许可证查询车辆信息
     */
    @ApiOperation(value = "通过车牌号和经营许可证查询车辆信息")
    @PostMapping("/getCarInfo")
    public Result<CarInfoReturnDto> getCarInfo(@RequestBody CarInfoReqDto reqDto) {
        reqDto.valid();
        return plateOwnerService.getCarInfo(reqDto);
    }

    /**
     * 申请第三步  车辆信息-->通过plateId查询查询车辆信息
     */
    @ApiOperation(value = "通过plateId查询")
    @PostMapping("/getCarInfo2")
    public Result<CarInfoReturnDto> getCarInfo2(@RequestBody CarInfoReq2Dto reqDto) {
        reqDto.valid();
        return plateOwnerService.getCarInfo2(reqDto);
    }

    /**
     * 申请第三步  车辆信息-->反馈车辆信息
     */
    @ApiOperation(value = "反馈车辆信息")
    @PostMapping("/postCarInfo")
    public Result<PostCarInfoResultDto> postCarInfo(@RequestBody PostCarInfoReqDto reqDto) {
        return plateOwnerService.postCarInfo(reqDto);
    }

    /**
     * 申请第四步  驾驶员信息-->通过驾驶员从业资格证和业户许可证查询驾驶员信息
     */
    @ApiOperation(value = "通过驾驶员从业资格证和业户许可证查询驾驶员信息")
    @PostMapping("/getDriverInfo")
    public Result<GetDriveInfoReturnDto> getDriverInfo(@RequestBody DriverInfoReqDto reqDto) {
        reqDto.valid();
        return plateOwnerService.getDriverInfo(reqDto);
    }

    /**
     * 申请第四步  驾驶员信息-->通过plateId查询驾驶员信息
     */
    @ApiOperation(value = "通过plateId查询驾驶员信息")
    @PostMapping("/getDriverInfo2")
    public Result<GetDriveInfoReturnDto2> getDriverInfo2(@RequestBody DriverInfoReq2Dto reqDto) {
        reqDto.valid();
        return plateOwnerService.getDriverInfo2(reqDto);
    }

    /**
     * 申请第四步  驾驶员信息-->更新或新增驾驶员信息
     */
    @ApiOperation(value = "反馈驾驶员信息")
    @PostMapping("/postDriver")
    public Result<?> postDriver(@RequestBody PostDriverInfoReqDto reqDto) {
        return plateOwnerService.postDriver(reqDto);
    }


    /**
     * 申请第四步  驾驶员信息-->反馈驾驶员信息
     */
    @ApiOperation(value = "删除驾驶员信息")
    @PostMapping("/deleteDriver")
    public Result<?> deleteDriver(@RequestBody @Validated DelDriverReqDto reqDto) {
        return plateOwnerService.deleteDriver(reqDto);
    }

    @PostMapping("/upload")
    @ApiOperation(value = "文件上传(测试专用)")
    public Result<?> uploadFile(@RequestPart("file") MultipartFile file, @ModelAttribute FileUploadReqDto reqDto) {
        return fileUploadService.uploadOss(file);
    }

    @PostMapping("/getFileById")
    @ApiOperation(value = "通过文件ID下载文件(测试专用)")
    public Result<?> getFileById(@RequestBody FileUploadReqDto reqDto) {
        return Result.success(fileUploadService.getFile(reqDto.getId()));
    }

    /**
     * 分页查询包车牌信息
     */
    @ApiOperation(value = "测试(测试专用)")
    @PostMapping("/test")
    public Result<?> test(MultipartHttpServletRequest request, HttpServletResponse response, @RequestParam("file") MultipartFile file, @RequestParam("id") String id) {

        String result = "";
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            // 上传运管的路径
            log.info("上传运管的接口路径 {}", CharterApplyLicense.UPLOAD_FILE_INFO);
            HttpPost httpPost = new HttpPost(CharterApplyLicense.UPLOAD_FILE_INFO);
            // 创建表单
            MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            builder.setCharset(Charset.forName("UTF-8"));
            builder.addBinaryBody("multipartFile", file.getInputStream(), ContentType.MULTIPART_FORM_DATA, file.getOriginalFilename());
            // 处理其他参数
            builder.addTextBody("id", id);

            HttpEntity httpEntity = builder.build();
            httpPost.setEntity(httpEntity);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity responseEntity = httpResponse.getEntity();
            if (responseEntity != null) {
                // 将响应内容转换为字符串
                result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
            }
//            resultMap = VehicleAttachmentController.receiveCharterLisenceData(key, result);

        } catch (Exception e) {
            log.error("上传运管出错 {}", e.getMessage());
            e.printStackTrace();
        }
        log.info("上传到运管的结果 {}", result);
        Map<String, String> stringStringMap = CharterApplyLicense.receiveCharterLicenseData(RtabTokenHelper.KEY, result);
        return Result.success(stringStringMap);
    }


    /**
     * 分页查询包车牌信息
     */
    @ApiOperation(value = "分页查询包车牌信息")
    @PostMapping("/getPlateDraftPageList")
    public Result<?> getPlateDraftPageList(@RequestBody @Validated PlateDraftPageReqDto reqDto) {
        return plateOwnerService.getPlateDraftPageList(reqDto);
    }

    /**
     * 分页查询包车牌信息
     */
    @ApiOperation(value = "删除草稿信息")
    @PostMapping("/delPlateDraft")
    public Result<?> delPlateDraft(@RequestBody @Validated DelPlateDraftReqDto reqDto) {
        return plateOwnerService.delPlateDraft(reqDto);
    }

    /**
     * 分页查询包车牌信息
     */
    @ApiOperation(value = "操作日志列表")
    @PostMapping("/operLogGet")
    public Result<?> operLogGet(@RequestBody @Validated OperLogGetReqDto reqDto) {
        return plateOwnerService.operLogGet(reqDto);
    }

    /**
     * 分页查询包车牌信息
     */
    @ApiOperation(value = "记录签发操作")
    @PostMapping("/savePlateSign")
    public Result<?> savePlateSign(@RequestBody @Validated PlateSaveReqDto reqDto) {
        return plateOwnerService.savePlateSign(reqDto);
    }

    @ApiOperation(value = "包车列表查看详情")
    @PostMapping("/plateInfoGet")
    public Result<PlateInfoGetResultDto> plateInfoGet(@RequestBody @Validated PlateInfoGetReqDto reqDto) {
        return plateOwnerService.plateInfoGet(reqDto);
    }

    @ApiOperation(value = "Excel导出包车牌申请数据")
    @PostMapping("/plateInfoExport")
    public Result<?> plateInfoExport(@RequestBody @Validated PlateDraftPageReqDto exportReqDto) {
        if (StringHelper.isEmpty(exportReqDto.getExportType()) || exportReqDto.getExportType().equals("1") || exportReqDto.getExportType().equals("2")) {
            return plateOwnerService.plateInfoExport(exportReqDto);
        } else {
            return Result.failed("请选择导出类型");
        }
    }

    @ApiOperation(value = "分页查询Excel导出记录")
    @PostMapping("/exportRecord")
    public Result<?> exportRecord(@RequestBody @Validated ExportRecordReqDto exportReqDto) {
        return plateOwnerService.exportRecord(exportReqDto);
    }

    /**
     * 分页查询包车牌信息
     */
    @ApiOperation(value = "接口测试正牌系统(测试专用)")
    @PostMapping("/test2")
    public Result<?> test2(@RequestBody Test2Vo test2Vo) {
        Map<String, String> map = CharterApplyLicense.gainCharterLicenseData(test2Vo.getMsg(), test2Vo.getPath());
        return Result.success(map.get("code"), map.get("data"));
    }


//    /**
//     * 文件上传并转换为PDF接口
//     * 支持单个文件（PDF或图片）或多张图片转换为PDF
//     */
//    @ApiOperation(value = "附件资料上传")
//    @PostMapping("/UploadFileAndStore")
//    public Result<?> uploadFileAndStore(UploadFileReqDto reqDto) {
//        // 参数校验
//        if (reqDto.getFiles() == null || reqDto.getFiles().length == 0) {
//            return Result.failed("请上传文件");
//        }
//        if (reqDto.getFileType() == null || reqDto.getFileType().trim().isEmpty()) {
//            return Result.failed("请指定文件类型");
//        }
//        if (reqDto.getFileType().equals("file0") || reqDto.getFileType().equals("file1") || reqDto.getFileType().equals("file2") || reqDto.getFileType().equals("file3") || reqDto.getFileType().equals("file4")) {
//        } else {
//            return Result.failed("文件类型不对。");
//        }
//        return plateOwnerService.uploadFileAndStore(reqDto);
//    }

    /**
     * 文件上传并转换为PDF接口
     * 支持单个文件（PDF或图片）或多张图片转换为PDF
     */
    @ApiOperation(value = "附件资料上传(ossId)")
    @PostMapping("/UploadFileAndStore2")
    public Result<?> uploadFileAndStore2(@RequestBody UploadFileReqDto2 reqDto) {
        // 参数校验
        if (reqDto.getFiles() == null || reqDto.getFiles().size() == 0) {
            return Result.failed("请上传文件");
        }
        if (reqDto.getFileType() == null || reqDto.getFileType().trim().isEmpty()) {
            return Result.failed("请指定文件类型");
        }
        if (reqDto.getFileType().equals("file0") || reqDto.getFileType().equals("file1") || reqDto.getFileType().equals("file2") || reqDto.getFileType().equals("file3") || reqDto.getFileType().equals("file4")) {
            if (reqDto.getFileType().equals("file3") || reqDto.getFileType().equals("file4")) {
                if (reqDto.getDriverId() == null) {
                    return Result.failed("请指定司机ID");
                }
            }
        } else {
            return Result.failed("文件类型不对。");
        }
        return plateOwnerService.uploadFileAndStore2(reqDto);
    }

    /**
     * 文件上传并转换为PDF接口
     * 支持单个文件（PDF或图片）或多张图片转换为PDF
     */
    @ApiOperation(value = "通过包车牌ID获取附件列表")
    @PostMapping("/GetUploadInfoByPlateId")
    public Result<?> GetUploadInfoByPlateId(@RequestBody @Validated GetUpLoadInfoReqDto reqDto) {
        return plateOwnerService.GetUploadInfoByPlateId(reqDto);
    }

    /**
     * 文件上传并转换为PDF接口
     * 支持单个文件（PDF或图片）或多张图片转换为PDF
     */
    @ApiOperation(value = "包车牌申请提交信息")
    @PostMapping("/saveApply")
    public Result<?> saveApply(@RequestBody @Validated GetUpLoadInfoReqDto reqDto) {
        return plateOwnerService.saveApply(reqDto);
    }

    /**
     * 分页查询包车牌信息
     */
    @ApiOperation(value = "根据文件地址下载文件(测试专用)")
    @PostMapping("/test3")
    public Result<?> test3(@RequestBody Test2Vo test2Vo) throws Exception {

        int lastSlashIndex = test2Vo.getPath().lastIndexOf('/');
        String fileName = lastSlashIndex >= 0 ? test2Vo.getPath().substring(lastSlashIndex + 1) : test2Vo.getPath();
        System.out.println(fileName);

        byte[] bytes = RtabHelper.downloadFromTransportation(test2Vo.getPath());

        File file = new File(fileName);
        // 自动创建父目录 + 写入文件
        FileUtils.forceMkdirParent(file);
        FileUtils.writeByteArrayToFile(file, bytes);
        return Result.success(file.getAbsolutePath());
    }

    @ApiOperation(value = "包车牌生成")
    @PostMapping("/generateCharterPlate")
    public Result<GeneratePlateResDto> generateCharterPlate(@RequestBody @Validated GeneratePlateReqDto reqDto) {
        return Result.success(plateGenerateService.generatePlate(reqDto));
    }

    @ApiOperation(value = "包车牌终止")
    @PostMapping("/stopCharterPlate")
    public Result<?> stopCharterPlate(@RequestBody @Validated StopCharterPlateReqDto reqDto) {
        return plateOwnerService.stopCharterPlate(reqDto);
    }

    @ApiOperation(value = " 已打印状态 纸质包车牌作废重打/归档")
    @PostMapping("/plateArchivedAndCancel")
    public Result<?> plateArchivedAndCancel(@RequestBody @Validated PlateArchivedAndCancelReqDto reqDto) {
        if (CharterPlateStatusEnum.ARCHIVED.getCode() == reqDto.getPlateOperType() || CharterPlateStatusEnum.REPRINT.getCode() == reqDto.getPlateOperType()) {
            return plateOwnerService.plateArchivedAndCancel(reqDto);
        } else {
            return Result.failed("包车牌当前操作类型只能是归档或作废重打");
        }
    }

    @ApiOperation(value = " 已生成电子包车牌归档")
    @PostMapping("/plateArchivedAndCancel2")
    public Result<?> plateArchivedAndCancel2(@RequestBody @Validated PlateArchivedAndCancelReqDto2 reqDto) {
        return plateOwnerService.plateArchivedAndCancel2(reqDto);
    }

    @ApiOperation(value = " 更新选中状态")
    @PostMapping("/taskUpdateState")
    public Result<?> taskUpdateState(@RequestBody @Validated PlateUpdateStatueReqDto reqDto) {
        return plateOwnerService.taskUpdateState(reqDto);
    }

    @ApiOperation(value = "打印补录")
    @PostMapping("/printSupplement")
    public Result<?> printSupplement(@RequestBody @Validated PlateUpdateStatueReqDto reqDto) {
        return plateOwnerService.printSupplement(reqDto);
    }

    @ApiOperation(value = "包车牌打印")
    @PostMapping("/printPlate")
    public Result<?> printPlate(@RequestBody @Validated PlatePrintReqDto reqDto) {
        return plateOwnerService.printPlate(reqDto);
    }

    @ApiOperation(value = "包车牌下载")
    @PostMapping("/downloadPlate")
    public Result<?> downloadPlate(@RequestBody @Validated PlatePrintReqDto reqDto) {
        return plateOwnerService.downloadPlate(reqDto);
    }
}
